import {
    Block,
    View,
    ScrollView,
    Swiper,
    SwiperItem,
    Text,
    Image,
    Button
  } from '@tarojs/components'
  import Taro from '@tarojs/taro'
  import withWeapp from '@tarojs/with-weapp'
  import './index.scss'
  const flow = require('../../utils/flow.js')
  const modules = require('./module.js')
  const { getUserInfo, transSuccToPro, onShow } = require('../../utils/util.js')
  const regeneratorRuntime = require('../../utils/async.js')
  
  const app = Taro.getApp()
  
  @withWeapp('Page')
  class _C extends Taro.Component {
    state = {
      userInfo: {},
      hasUserInfo: false,
      canIUse: Taro.canIUse('button.open-type.getUserInfo'),
      articles: {}, // 每页view的文章 [ { articles: [], pageIndex: 1, total: 100, hasMore: false } ]
      myTags: [], // 用户订阅的tag
      tagList: [],
      showTagPanel: false,
      tags: [],
      tagCls: {},
      tagSaveTips: '',
      tagSaveCls: 'tag-save unselected',
      shadowCls: 'shadow',
      selectedTag: '我的', // 当前选中的tag
      toView: 'toView0', // 当前选中tag对应的panel
      scrollLeft: '200rpx',
      headerViewItem: '', // 当前选中tag对应的header-item
      statusBarHeight: app.globalData.statusBarHeight,
      swiperHeight: app.globalData.contentHeight + 33,
      swiperTopHeight: app.globalData.headerHeight + 33
    }
    onLoadMore = async e => {
      // const { name } = e.target.dataset
      const { selectedTag, articles } = this.data
      const curTag = articles[selectedTag]
  
      if (curTag.hasMore) {
        await this.flow.dispatch('loadMore', {
          tagName: selectedTag,
          pageIndex: curTag.pageIndex + 1
        })
      }
    }
    navigate = e => {
      const sid = e.currentTarget.dataset.sid
      Taro.navigateTo({ url: `../detail/index?id=${sid}` })
    }
    init = async () => {
      console.log('wxlogin start')
      const loginRes = await transSuccToPro(wx.login.bind(wx))
      // 发送 res.code 到后台换取 openId, sessionKey, unionId
      await this.flow.dispatch('wxlogin', {
        appname: 'avote',
        code: loginRes.code
      })
  
      console.log('wxlogin done')
      await this.flow.dispatch('getList', { key: '我的' })
  
      console.log('me start')
      await this.flow.dispatch('getMeAndTags') 
  
      // 缓存其他tag
      await this.flow.dispatch('getArtsByTags')
  
      console.log('all start')
    }
    componentWillMount = async () => {
      this.flow = new flow(
        this,
        modules
      )
      this.init();
      //Taro.startPullDownRefresh;
  
      setTimeout(() => {
        
      }, 2000)
    }
    onPullDownRefresh() {
      console.log('onPullDownRefresh', '下拉刷新....');
      setTimeout(() => {
        Taro.stopPullDownRefresh();//停止下拉动作过渡
        Taro.showToast({
          title: `更新了10条内容`,
          icon: 'none'
        });
      }, 2000)
    }
    onRefresh = () => {
      Taro.startPullDownRefresh()//停止下拉动作过渡
    }
    setTag = e => {
      const { tags, tagCls, tagList } = this.data
      const name = e.currentTarget.dataset.name
  
      if (tagCls[name]) {
        tags.splice(tags.findIndex(tag => tag === name), 1)
        delete tagCls[name]
      } else {
        tags.push(name)
        tagCls[name] = 'tag-item tag-item-selected'
      }
  
      this.setState({
        tags,
        tagCls,
        tagSaveTips: `${tags.length}/${tagList.length}`,
        tagSaveCls: tags.length ? 'tag-save' : 'tag-save unselected'
      })
    }
    saveTags = () => {
      const { tags } = this.data
  
      if (tags.length) {
        this.flow.dispatch('saveTags', { tags })
      }
    }
    onTagChange = async e => {
      const { myTags } = this.data
      const tag = e.currentTarget.dataset.name
      const param =
        tag === '我的'
          ? {}
          : {
              tag
              // const list = await this.flow.dispatch('getList', param);
            }
      this.setState({
        toView: `toView${myTags.findIndex(t => t === tag)}`,
        selectedTag: tag
      })
    }
    catchtouchend = () => {
      const { viewIndex } = this
      const { myTags } = this.data
  
      this.setState({
        toView: `toView${viewIndex}`,
        selectedTag: myTags[viewIndex]
      })
    }
    onScroll = e => {
      const { myTags } = this.data
      const { current } = e.detail
  
      this.setState({
        toView: `toView${current}`,
        selectedTag: myTags[current],
        headerViewItem: `item${current}`
      })
    }
    componentDidShow = onShow
    config = {
      navigationBarTitleText: '',
      enablePullDownRefresh: true,
    }
  
    render() {
      const {
        statusBarHeight: statusBarHeight,
        headerViewItem: headerViewItem,
        selectedTag: selectedTag,
        myTags: myTags,
        toView: toView,
        swiperHeight: swiperHeight,
        swiperTopHeight: swiperTopHeight,
        articles: articles,
        showTagPanel: showTagPanel,
        tagSaveTips: tagSaveTips,
        tagCls: tagCls,
        tagList: tagList,
        tagSaveCls: tagSaveCls
      } = this.state
  
      return (
        <View>
          <View className="refreash-container" onTap={this.onRefresh}> 
            <Text className="fa fa-refresh fa-lg" />
          </View>
          <View className="page-header">
            <View style={'height: ' + statusBarHeight + 'px'} />
            <View className="page-title">关注</View>
          </View>
          <ScrollView
            className="page-container"
            scrollWithAnimation="true"
            onChange={this.onScroll}
            currentItemId={toView}
            scrollY="true" 
            style={
              'height: ' + swiperHeight + 'px;'
            }
          >
            <View className="scroll-left watch-container"> 
              <View>我的关注</View>
              <ScrollView
                scrollIntoView={headerViewItem}
                style="white-space: nowrap; display: block"
                className="showmian"
                scrollX="true"
                scrollWithAnimation="false"
              >
                {myTags.map((item, index) => {
                  return (
                    <View
                      className={
                        (selectedTag === item ? 'hover' : '') +
                        ' w20 showmain-txt'
                      }
                      onClick={this.onTagChange}
                      data-name={item}
                      id={'item' + index}
                    >
                      <View className="showmain-item-txt">{item}</View>
                    </View>
                  )
                })}
              </ScrollView>
            </View>
            <View
              className="page"
              scrollY="true" 
              style="height:100%"
              onScrollToLower={this.onLoadMore}
            >
              <View className="article-container">
                {articles['我的'].articles.map((article, index) => {
                  return (
                    <View
                      className="article"
                      onClick={this.navigate}
                      data-sid={article.id}
                    >
                      <View className="article-header">
                        <Image src={article.user_img} className="article-author-photo"/>
                        <Text className="article-author-name">{article.user_name}</Text>
                        <Text className="article-time">{article.published}</Text>
                      </View>
                      <View className="article-inner">
                        <View className="article-info">
                          <Text className="article-title">
                            {article.title}
                          </Text>
                          <View className="article-footer">
                            <View className="footer-item">
                              <Text className="fa fa-thumbs-o-up"/>
                              <Text className="footer-num">{article.likenum}</Text>
                            </View>
                            <View className="footer-item">
                            <Text className="fa fa-commenting-o"/>
                              <Text className="footer-num">{article.commentnum}</Text>
                            </View>
                            <View className="footer-item">
                            <Text className="fa fa-eye"/>
                              <Text className="footer-num">{article.hitnum}</Text>
                            </View>
                          </View>
                        </View>
                        <View className={article.articleImageVisible}>
                          <Image src={article.post_img} />
                        </View>
                      </View>
                    </View>
                  )
                })}
                <View
                  className={
                    articles['我的'].showLoading ? 'more-arts' : 'hide'
                  }
                >
                  加载中..
                </View>
                <View
                  className={
                    articles[tag].hasMore ? 'hide' : 'no-more-arts'
                  }
                >
                  --没有更多内容了--
                </View>
              </View>
            </View>
          </ScrollView>
          <View className={showTagPanel ? 'shadow' : 'hide'} />
          <View className={showTagPanel ? 'tag-panel' : 'hide'}>
            <View className="tag-setting">
              <View className="tag-title">
                {'请选择感兴趣的标签' +
                  (tagSaveTips ? '(' + tagSaveTips + ')' : '')}
              </View>
              <View className="tag-panel-container">
                {tagList.map((item, index) => {
                  return (
                    <View
                      className={
                        (tagCls[item.name] || 'tag-item') +
                        ' ' +
                        (item.pos ? 'hidden' : '')
                      }
                      onClick={this.setTag}
                      data-name={item.name}
                    >
                      {item.name}
                    </View>
                  )
                })}
              </View> 
              <Button onClick={this.saveTags} className={tagSaveCls}>
                保存
              </Button>
            </View>
          </View>
        </View>
      )
    }
  }
  
  export default _C
  